//
//  PPUnreadMessageManager.m
//  pickpic
//
//  Created by Jinxiao on 10/7/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPUnreadMessageManager.h"

@interface PPUnreadMessageManager ()
@property (readwrite, nonatomic, strong) NSTimer *timer;
@end

@implementation PPUnreadMessageManager

+ (instancetype)sharedInstance {
    static id instance;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        instance = self.new;
    });

    return instance;
}

- (instancetype)init {
    self = [super init];

    [self reloadCache];

    _timer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(timerDidFired) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

    return self;
}

- (NSString *)cacheFilePath {
    NSString *directory = [NSString stringWithFormat:@"%@_UnreadMessageSummaries", DGCurrentAccount.userID];
    NSString *path = [[[NSFileManager defaultManager] documentDirectory] stringByAppendingPathComponent:directory];

    return path;
}

- (void)reloadCache {
    NSData *data = [NSData dataWithContentsOfFile:[self cacheFilePath]];

    if(data != nil) {
        _summaries = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
}

- (void)timerDidFired {
    [self fetchUnreadMessages];
}

- (void)setSummaries:(NSArray<PPUnreadMessageSummaryObject *> *)summaries {

    [self willChangeValueForKey:@"summaries"];

    _summaries = summaries;

    [NSKeyedArchiver archiveRootObject:_summaries toFile:[self cacheFilePath]];

    [[NSNotificationCenter defaultCenter] postNotificationName:PPUnreadMessageSummaryDidChangeNotification object:nil];

    [self didChangeValueForKey:@"summries"];
}

- (void)fetchUnreadMessages {

    if(DGCurrentAccount.userID.length == 0) {
        return;
    }

    [PPNetworkService fetchMessageSummaryWithOnlyUnread:YES after:nil callback:^(id data, NSError *error) {
        NSMutableArray *summaries = [NSMutableArray array];

        for(NSDictionary *parameters in [data validArray]) {
            PPUnreadMessageSummaryObject *summary = [PPUnreadMessageSummaryObject summaryForParameters:parameters];
            [summaries addObject:summary];
        }

        self.summaries = summaries;
    }];

}

- (PPUnreadMessageSummaryObject *)summaryForType:(PPUnreadMessageSummaryType)type {
    __block PPUnreadMessageSummaryObject *summary = nil;

    [_summaries enumerateObjectsUsingBlock:^(PPUnreadMessageSummaryObject *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        if(obj.type == type) {
            summary = obj;
            *stop = YES;
        }
    }];

    return summary;
}

- (void)markSummariesAsReadForType:(PPUnreadMessageSummaryType)type {
    NSMutableArray *summaries = [NSMutableArray array];

    [_summaries enumerateObjectsUsingBlock:^(PPUnreadMessageSummaryObject *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        if(obj.type != type) {
            [summaries addObject:obj];
        }
    }];

    self.summaries = summaries;
}

@end

NSString *const PPUnreadMessageSummaryDidChangeNotification = @"PPUnreadMessageSummaryDidChangeNotification";
